//聊天
var basePage = require('../../common/BasePage');
// var baseList = require('../../common/BaseList');
var app = getApp()
var SocketTask = app.globalData.SocketTask;
var socketOpen = false;
Page({
	behaviors: [basePage],
	data: {
		reqUrl: '',
		scrollIndex: "a9", //令页面滚动到最新一条消息
		scrollTop: 1000000,
		isVoice: false,
		voiceState: 0, //1取消发送语音
		characters: "", //发送的文字
		sendList: [],
		serviceInfo: {},//客服信息
		myInfo: {},//我的信息
		message: [],
		current_page: 1, //当前页
		pages: 1, //总页面
		loading: false,
		historyList: [],
		refresh: true,

	},

	onLoad: function(options) {

		this.setData({
			serviceInfo: JSON.parse(options.serviceInfo),
			myInfo: JSON.parse(options.myInfo),
		})
		this.webSocket()
		this.getHistory()
	},
	// 页面加载完成
	onReady: function() {

	},
	//重发
	return_msg(e) {
		console.log("****", e)
		var sendIndex = e.currentTarget.dataset.index
		var list = this.data.sendList
		var returnMsg = list[sendIndex]
		list.splice(sendIndex, 1)
		console.log("新的数组", list)
		this.setData({
			sendList: list
		})
		console.log("需要重发的消息", returnMsg)
		this.sendData(returnMsg.clsContent.content, returnMsg.clsContent.type)

	},

	//查询历史消息
	getHistory() {
		this.request({
			url: this.data.host + "/home/chat/log",
			data: {
				toid: this.data.serviceInfo.id,
				page: this.data.current_page
			},
			method: "GET"
		}, res => {
			console.log("历史消息", res)
			if (res.data.length > 0) {
				var list = this.data.historyList
				var content = res.data.reverse()
				var arr = [{
					time: content[0].timestamp,
					sendList: content
				}]
				arr = arr.concat(list)
				this.setData({
					loading: false,
					historyList: arr,
					pages: res.pages,
					refresh: true,
					scrollIndex: 'a' + (res.data.length - 1)
				})
			}

		})
	},
	webSocket: function() {
		getApp().globalData.onMessage = this.onMessage;
	},
	onMessage(msg) {
		console.log("聊天列表", msg)
		var that = this
		if (msg.type == "friend") {
			if (this.data.serviceInfo.id == msg.id) {
				var list = this.data.sendList
				list.push(msg)
				console.log("列表", list)
				that.setData({
					sendList: list,
					scrollIndex: 'b' + (list.length - 1)
				})
				//如果收到消息，将该消息设置为已读
				var readmsg={
					type:'read_msg',
					id:this.data.myInfo.id,
					toid:this.data.serviceInfo.id
				}
				app.globalData.SocketTask.send({
					data: JSON.stringify(readmsg),
					success: function(res) {
						console.log('发送成功', res)
					},
					fail: function(err) {
						console.log("发送失败", err)
						// that.webSocket()
						
					},
				})
			}

		}

	},
	//按住说话
	startVoice() {
		console.log("按住")
		this.setData({
			voiceState: 0
		})
		// wx.showToast({
		// 	title: '录音中···',
		// 	image: '../../assets/microphone.png',
		// 	duration: 1000000000
		// })
		wx.getRecorderManager().start({
			duration: 10000,
		})
	},
	//松手发送语音
	endVoice() {
		console.log("结束1")
		wx.hideToast()
		if (this.data.voiceState == 1) return;
		wx.getRecorderManager().onStop((res) => {
			console.log("****语音*****", res)
			// if (!this.data.inpvalue) {
			// 	wx.showLoading({
			// 		title: '语音识别中'
			// 	})
			// }
		})
		wx.getRecorderManager().stop((res) => {
			console.log("结束语音", res)
		})

	},
	//取消录音
	moveVoice(e) {
		// console.log("取消", e)
		this.setData({
			voiceState: 1
		})
	},
	//发送文字
	sendText() {
		var that = this
		console.log("发送", this.data.characters)
		var characters=this.data.characters
		if(!characters.trim()){
			that.setData({
				characters:''
			})
		   wx.showToast({
		   	title: '发送内容不能为空',
		   	icon:"none",
		   	duration: 1000
		   })
		   return;
		}
		characters =characters.replace(/^\s*|\s* $/g , "")
		that.sendData(characters, 'text')
	},

	//选择图片
	imgUplod() {
		var that = this
		wx.chooseImage({
			count: 9,
			sizeType: ['original', 'compressed'],
			sourceType: ['camera','album'], //album相册
			success(res) {
				console.log("选择图片", res)
				const tempFilePaths = res.tempFilePaths;
				wx.uploadFile({
					url: that.data.host + "/home/upload/image",
					filePath: tempFilePaths[0],
					name: 'image',
					formData: {
						from: 'chat'
					},
					success: function(res) {

						console.log("图片上传", JSON.parse(res.data))
						var image = JSON.parse(res.data)
						var img = that.data.imgHost + "/" + image.data.path
						that.sendData(img, 'image')
					}
				})
				// tempFilePath可以作为img标签的src属性显示图片
				// const tempFilePaths = res.tempFilePaths
			}
		})
	},
	//视频上传
	videoUplod() {
		var that = this
		wx.chooseVideo({
			sourceType: ['camera','album'], //album相册
			success: function(res) {
				console.log("视频", res)
				const tempFilePaths = res.tempFilePath;
				wx.uploadFile({
					url: that.data.host + "/home/upload/video",
					filePath: tempFilePaths,
					name: 'file',
					success: function(res) {

						console.log("视频", JSON.parse(res.data))
						var videoRes = JSON.parse(res.data)
						var video = that.data.imgHost + "/" + videoRes.data.path
						that.sendData(video, 'video')

					}
				})
			}
		})
	},
	sendData(data, type) { //type=text文字，image图片,video视频,file文件（文件只做接收下载）
		console.log("socket连接状态",getApp().globalData.showSocket)
		if(!getApp().globalData.showSocket){
			wx.showModal({
			  title: '客服系统已断开',
			  content: '请确定是否重连',
			  success (res) {
			    if (res.confirm) {
			      console.log('用户点击确定')
				  getApp().globalData.number=0
				  getApp().globalData.againSocket=1
				  getApp().connectSocket();
				  
			    } else if (res.cancel) {
			      console.log('用户点击取消')
			    }
			  }
			})
			return;
		}
		if (getApp().globalData.number >= 3) {
			wx.showToast({
				title: '聊天服务异常，请重启小程序或者联系客服',
				icon: 'none',
				duration: 2000
			})
			return;
		}
		if (!socketOpen) {
			this.webSocket()
		}
		var mine_data = {
			id: this.data.myInfo.id,
			username: this.data.myInfo.username,
			avatar: this.data.myInfo.avatar,
			mine: 1,
			content: data,
			timestamp: new Date().getTime()
		}
		if (type == 'image') {
			mine_data.content = 'img[' + data + ']'
		} else if (type == 'video') {
			mine_data.content = 'video[' + data + ']'
		} else {
			mine_data.content = data
		}
		var to_data = {
			id: this.data.serviceInfo.id,
			uesername: this.data.serviceInfo.username,
			avatar: this.data.serviceInfo.avatar,
			type: "friend"
		}
		var dataMsg = {
			type: "chatMessage",
			data: {
				mine: mine_data,
				to: to_data
			}
		}

		var list = this.data.sendList
		list.push(mine_data)
		var listIndex = list.length - 1
		list[listIndex].loding = true
		var clsContent = {
			type: type,
			content: data
		}
		list[listIndex].clsContent = clsContent
		console.log("***发送***", list)
		this.setData({
			sendList: list,
			characters: "",
			scrollIndex: 'b' + (list.length - 1)
		})
		console.log("发送", mine_data)

		this.SocketSend(dataMsg, listIndex)
	},
	//发送
	SocketSend(data, listIndex) {
		var that = this
		var list = this.data.sendList
		app.globalData.SocketTask.send({
			data: JSON.stringify(data),
			success: function(res) {
				console.log('发送成功', res)
				list[listIndex].loding = false
				that.setData({
					sendList: list
				})
				console.log("list", list)
			},
			fail: function(err) {
				console.log("发送失败", err)
				list[listIndex].loding = false
				list[listIndex].error = true
				that.setData({
					sendList: list
				})
				// that.webSocket()
				if (socketOpen) {

				}
				// that.sendData(list[listIndex].content)
			},
		})
	},
	clickVoice() {
		// this.data.isVoice=!this.data.isVoice
		this.setData({
			isVoice: !this.data.isVoice
		})
	},
	/**格式化列表中的数据 */
	init_val(val, index, arr) {

	},
	//下拉查询历史信息
	myOnPullDownRefresh() {
		var refresh = this.data.refresh
		if (refresh) {
			this.setData({
				refresh: false
			})
			// console.log("*****xiala", this.data.pages, "**", this.data.current_page)


			if (this.data.pages <= this.data.current_page) {
				// console.log("&&&&&&&")
				return;
			}
			// console.log("^^^^^^^^^^")
			this.setData({
				loading: true
			})
			setTimeout(() => {
				var current_page = (Number(this.data.current_page) + 1)
				this.setData({
					current_page: current_page
				})
				// console.log("********", this.data.current_page)
				this.getHistory()
			}, 2000)
		}


	}
})
